<?php

Raise::load('core.RaiseCollection');
Raise::load('control.RaiseFormField');

/**
 * RaiseDropDownField UIControl class
 * A drop down view control
 *
 * @author Sam-Mauris Yong <hellclanner at live dot com>
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package Raise.Core.UI.Form
 * @since 1.2
 */
class RaiseDropDownField extends RaiseFormField {

    /**
     * A collection of drop down options with each drop down option's value as key and text as value.
     * @var RaiseCollection
     */
    private $data;

    /**
     * The value of the selected option
     * @var string|integer
     */
    private $selected = null;

    /**
     * Create new RaiseDropDownField
     * @param string $name (optional) The unique identifier of this dropdown field
     * @param RaiseCollection $data (optional) The data
     */
    function __construct($name = null, $data = null) {
        $this->data = new RaiseCollection();
        $this->tag = RaiseHtml::tag('select');
        if(func_num_args() >= 1){
            $this->clientId($name);
        }

        if(func_num_args() >= 2){
            $this->data = ($data instanceof RaiseCollection ? $data->raiseClone() : $data);
        }
    }

    /**
     * Get the collection of drop down options with each drop down option's value as key and text as value.
     * @return RaiseCollection
     */
    public function data(){
        return $this->data;
    }

    /**
     * Get or set the selected option
     * @param integer|string $s (optional) Set the select option
     * @return integer|string
     */
    public function selected($s = null){
        if(func_num_args() == 1){
            $this->selected = $s;
        }
        return $this->selected;
    }

    public function output() {
        if($this->clientId()){
            $this->tag->attributes()->add('id', $this->clientId());
            $this->tag->attributes()->add('name', $this->clientId());
        }
        if($this->cssClass()){
            $this->tag->attributes()->add('class', $this->cssClass());
        }
        $d = '';
        foreach($this->data as $k => $v){
            $a = array();
            if($k == $this->selected){
                $a['selected'] = 'selected';
            }
            $tag = RaiseHtml::tag('option', $v, $a);
            $tag->attributes()->add('value', $k);
            $d .= $tag->html();
        }
        $this->tag->value($d);
        return $this->tag->html();
    }

}
